const { Chat } = require('../model')

const { createToken } = require('../middleware/jwt')

class ChatController {
  // 登录
  async login(ctx, next) {
    const { username, password } = ctx.request.body
    const result = await Chat.findOne({ username })
    let res = { flag: true, msg: '登录成功！', data: result, token: ''}
    console.log('登录结果：', result)
    if (result) {
      if (result.password !== password) {
        res.msg = '密码错误~'
        res.flag = false
      }
      const token = createToken(username)
      res.token = token
      console.log(result)
      ctx.body = res
    } else {
      res.msg = '查无此人~'
      res.flag = false
      ctx.body = res
    }
  }
  
  // 注册
  async register(ctx, next) {
    const { username, password, nickname, signature } = ctx.request.body
    const result = Chat.findOne({ username })
    console.log('注册：', username, password, nickname, signature)
    if (!result) {
      const user = new Chat({username, password, nickname, signature})
      await user.save()
      ctx.body = { msg: '注册成功！', flag: true, data: '' }
    } else {
      ctx.body = { msg: '此用户已存在！', flag: false, data: '' }
    }
  
  }
}

module.exports = new ChatController()